package com.tul.exercise.base.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * @author tuliang
 *         工具类
 */
public class Print {

    /**
     * 打印方法
     *
     * @param obj 对象
     */
    public static void print(Object obj) {
        System.out.println(obj);
    }

    /**
     * 打印方法
     *
     * @param obj 对象
     */
    public static void println(Object obj) {
        System.out.println(obj);
    }

    /**
     * 打印方法
     *
     * @param obj 对象
     */
    public static void printb(Object obj) {
        System.out.print(obj);
    }

    /**
     * @param s
     * @param i
     */
    public static void printBinaryInt(String s, int i) {
        print(s + ", int: " + i + ", binary:\n      " + toPrettyBinaryString(i));
    }

    public static void printBinaryLong(String s, long i) {
        print(s + ", int: " + i + ", binary:\n      " + toPrettyBinaryString(i));
    }

    /**
     * 产生int数字的二进制字符串
     *
     * @param num 数字
     * @return 二进制字符串
     */
    public static String toPrettyBinaryString(int num) {
        String str = Integer.toBinaryString(num);
        return toPrettyStr(str);
    }

    /**
     * 产生int数字的二进制字符串
     *
     * @param num 数字
     * @return 二进制字符串
     */
    public static String toPrettyBinaryString(long num) {
        String str = Long.toBinaryString(num);
        return toPrettyStr(str);
    }

    /**
     * 将二进制字符串以8位插入"_",产生更易读的二进制字符串格式
     *
     * @param binaryStr 数字的二进制字符串格式
     * @return String 如 "1010_1011110_0110111_1011111_0101011_11001110"
     */
    private static String toPrettyStr(String binaryStr) {
        if (StringUtils.isBlank(binaryStr)) {
            return null;
        }
        int len = binaryStr.length();
        int m = len / 8;
        int n = len % 8;


        String reserveSrcStr = (new StringBuilder(binaryStr)).reverse().toString();

        StringBuilder strStr = new StringBuilder(binaryStr);
        strStr.reverse();

        StringBuilder result = new StringBuilder("");

        // 整除部分
        for (int i = 0; i < m; i++) {
            result.append(reserveSrcStr.substring(i * 8, (i + 1) * 8));
            result.append("_");
        }

        // 余数部分
        if (n > 0) {
            result.append(reserveSrcStr.substring(m * 8, len));
        }

        // 去掉尾部的"_"
        if (n == 0) {
            int newLen = m*8+m;
            result = result.replace(newLen-1, newLen, "");
        }
        return result.reverse().toString();
    }


    public static void main(String[] args) {
        StringBuilder str = new StringBuilder("0000000x_");
        System.out.println(str);

        str.replace(8, 9, "");
        System.out.println(str.toString());
    }
}
